import { CountUp } from './countUp.min.js';

$(document).ready(function() {
    //启用积分
    $("input[name='credit-switch']").on("change", function () {
        //checkbox选中判断
        var change = $("input[type='checkbox']").is(':checked');

        //最大可抵扣金额
        var max_value = Math.floor(localStorage.getItem("ensure-cn") / 2);

        //可用积分
        var credit_score = $('#creditScore').attr('data-credit-score');

        if (change) {
            $('.pay-checkout small').show();
            $('#creditTarget').text(parseFloat(localStorage.getItem("ensure-cn") - localStorage.getItem("credit_value")).toFixed(2));

            //开启积分，实际可抵扣金额
            if(parseFloat(credit_score) / 100 <= max_value) {
                localStorage.setItem("credit_value", parseFloat(credit_score) / 100);
                $('.pay-checkout small').text('(积分抵扣:￥' + localStorage.getItem("credit_value") + '.00)');
            } else {
                localStorage.setItem("credit_value", max_value);
                $('.pay-checkout small').text('(积分抵扣:￥' + localStorage.getItem("credit_value") + '.00)');
            }

            //金额动画 if删除后将无法正常工作
            const options = {
                startVal: localStorage.getItem("ensure-cn"),
                decimalPlaces: 2,
            };
            let demo = new CountUp('creditTarget', parseFloat(localStorage.getItem("ensure-cn") - localStorage.getItem("credit_value")).toFixed(2), options);
            if (!demo.error) {
                demo.start();
            } else {
                console.error(demo.error);
            }
        } else {
            $('.pay-checkout small').hide();
            $('#creditTarget').text(parseFloat(localStorage.getItem("ensure-cn")));

            //金额动画 if删除后将无法正常工作
            const options = {
                startVal: parseFloat(localStorage.getItem("ensure-cn") - localStorage.getItem("credit_value")).toFixed(2),
                decimalPlaces: 2,
            };
            let demo = new CountUp('creditTarget', localStorage.getItem("ensure-cn"), options);
            if (!demo.error) {
                demo.start();
            } else {
                console.error(demo.error);
            }

            //不使用积分
            localStorage.setItem("credit_value", 0);
        }
    })
})
